package pwsaver;

import java.io.IOException;
import javax.servlet.http.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;


import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

@SuppressWarnings("serial")
public class PinDaoServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(PinDaoServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null) {
			resp.sendRedirect(userService.createLoginURL(req
					.getRequestURI()));
			return;
		}
		try {
			PinInfoDAO pinInfoDAO = new PinInfoDAO();
			UserInfo userInfo= pinInfoDAO.getOrCreateUserInfo(user);
			
			PinInfo pinInfo1 = new PinInfo();
			pinInfo1.setSource("Google");
			pinInfo1.setAccount("siben");
			pinInfo1.setPin("testpin1");
			pinInfo1.setType("Search");
			pinInfo1.setComment("used for test");
			pinInfo1.setModifyDate(new Date());
			
			PinInfo pinInfo2 = new PinInfo();
			pinInfo2.setSource("China mobile");
			pinInfo2.setAccount("1363162");
			pinInfo2.setPin("testpin2");
			pinInfo2.setType("Commercial");
			pinInfo2.setComment("used for test 2");
			pinInfo2.setModifyDate(new Date());
			
			pinInfoDAO.UpdatePinInfo(userInfo, Arrays.asList(pinInfo1,pinInfo2));
			
			List<PinInfo> pinInfos = pinInfoDAO.getPinInfoList(userInfo);
			
			log.info(String.format("User {0} has been created.",user.getNickname()));
			//resp.sendRedirect("showdata.jsp");
			//resp.setContentType("text/plain");
			//resp.getWriter().println("Save successful, " + user.getNickname());
			// resp.sendRedirect("/guestbook.jsp?guestbookName=" +
			// guestbookName);
		} catch (Exception e) {
			log.warning("Save record for " +user.getNickname()+"Error!" );
			log.warning(e.getMessage());
		}
	}

}
